import { Injectable } from '@angular/core';

import { QuoteBasic } from 'service/QuoteBasic';
import { IBIASService } from 'interface/IBIASService';
import { EMAService } from 'service/EMAService';

@Injectable()
export class BIASService implements IBIASService {

  constructor(private emaService:EMAService) {

  }

  private _cacuBias(list, start, end, nowClose) {
    let sum = 0;

    // if(start === end) {
    //   return null;
    // }

    for(let j=start; j<=end; j++) {
      sum+=list[j];
    }

    if (sum === 0) {
      return 0;
    } else {
      let average = sum / (end - start + 1);

      let bias = ((nowClose - average) / average * 100).toFixed(3);

      return parseFloat(bias);
    }
  }

  compute(quote:QuoteBasic, day:number):Array<any> {
    const biasList = [];
    const count = quote.close.length;
    const emaList = this.emaService.compute(quote,day);

    if(day > 0){
      for(let i=0; i<count; i++) {
        if(i < day) {
          biasList.push(this._cacuBias(quote.close, 0, i, quote.close[i]));
          continue;
        }
        biasList.push(this._cacuBias(quote.close, i - day + 1, i, quote.close[i]));
      }
    }
    return biasList;
  }

  update(quote:QuoteBasic, day:number, oldList:Array<any>):Array<any> {
    const oldCount = oldList.length;
    const originCount = quote.close.length;

    if(originCount > 0 && day > 0){

      if(oldCount === 0){
        return this.compute(quote,day);
      }

      const start = (originCount - day) < 0 ? 0 : (originCount - day);
      const end = (originCount - 1) < 0 ? 0 : (originCount - 1);
      // const emaList = this.emaService.compute(quote, day);
      const times = quote.time;

      const temp = this._cacuBias(quote.close, start, end, quote.close[end]);

      if (oldCount < originCount) {
        oldList.push( temp);
      } else {
        oldList[end] = temp;
      }
    }

    return oldList;
  }
}
